/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package startupsolutions.mobilize;

import java.io.IOException;
import java.io.PrintWriter;
import javax.jdo.PersistenceManager;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author ultimoistante
 */
public class LoginServlet extends HttpServlet
	{
	/**
	 * Handles the HTTP
	 * <code>GET</code> method.
	 *
	 * @param request servlet request
	 * @param response servlet response
	 * @throws ServletException if a servlet-specific error occurs
	 * @throws IOException if an I/O error occurs
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
		{
		//processRequest(request, response);
		HttpSession session = request.getSession(true);
		try
			{
			/*
			// manually creates an user
			UserBean persistuser = new UserBean();
			persistuser.setUserName("admin");
			persistuser.setPassword("admin");
			PersistenceManager pm = PMF.get().getPersistenceManager();
			pm.makePersistent(persistuser);
			pm.close();*/
			
			
			
			session.setAttribute("error", "invalid username or password");
			//
			UserBean user = new UserBean();
			user.setUserName(request.getParameter("username"));
			user.setPassword(request.getParameter("password"));
			//
			user = UserDAO.login(user);
			//
			if(user.isValid())
				{
				session.removeAttribute("error");
				session.setAttribute("currentSessionUser", user);
				//response.sendRedirect("/admin.jsp"); //logged-in page      		
				//response.forward("/admin.jsp"); //logged-in page 
				
				String nextJSP = "/admin.jsp";
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
				dispatcher.forward(request,response);
				
				
				}
			else
				{
				response.sendRedirect("/login.jsp"); //logged-in page      		
				}
			}
		catch(Throwable theException)
			{
			response.sendRedirect("/login.jsp"); //logged-in page      		
			System.out.println(theException);
			}
		}
	}
